package org.sample.springboot.validator;

import java.util.Set;
import java.util.function.Consumer;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.log4j.Logger;

public class ValidateHelper {

	private static final Logger LOGGER = Logger.getLogger(ValidateHelper.class);
	
	private Validator validator;
	
	private final Consumer<ConstraintViolation<?>> violationConsumer;

	public ValidateHelper() {
		initializeValidator();
		this.violationConsumer = null;
	}
	
	public ValidateHelper(Consumer<ConstraintViolation<?>> violationConsumer) {
		initializeValidator();
		this.violationConsumer = violationConsumer;
	}
	
	private void initializeValidator() {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		this.validator = factory.getValidator();
	}

	/**
	 * Validate all constraints on {@code object}, and convert violation to
	 * {@link #ErrorInfo }.
	 * 
	 * @param object
	 *            object to validate
	 * @param groups
	 *            the group or list of groups targeted for validation (defaults
	 *            to {@link Default})
	 */
	public void validate(Object object, Class<?>... groups) {

		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
		if (!constraintViolations.isEmpty()) {
			for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
				String message = constraintViolation.getMessage();
				String path = constraintViolation.getPropertyPath().toString();

				LOGGER.info(message);
				LOGGER.info(path);
				
				if (violationConsumer != null) {
					violationConsumer.accept(constraintViolation);
				}
			}
		}
	}

}
